package cn.jiyun.service.impl;

import cn.jiyun.mapper.CampusMapper;
import cn.jiyun.mapper.JobMapper;
import cn.jiyun.mapper.MajorMapper;
import cn.jiyun.mapper.StudentMapper;
import cn.jiyun.pojo.Campus;
import cn.jiyun.pojo.Job;
import cn.jiyun.pojo.Major;
import cn.jiyun.pojo.Student;
import cn.jiyun.res.JsonRes;
import cn.jiyun.service.MajorService;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

@Service
public class MajorServiceImpl implements MajorService {
    @Autowired
    MajorMapper majorMapper;
    @Autowired
    CampusMapper campusMapper;
    @Autowired
    JobMapper jobMapper;
    @Autowired
    StudentMapper studentMapper;
    @Override
    public Page<Major> findPage(Integer pageNum, Integer pageSize, Major major) {
        Page<Major> majorPage = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Major> lm = new LambdaQueryWrapper<>();
        lm.eq(major.getCid()!= null,Major::getCid,major.getCid());
        lm.like(Major::getName,major.getName());
        List<Major> majors = majorMapper.selectList(lm);
         majorPage.setRecords(majors);
        List<Major> records = majorPage.getRecords();
        for (Major record : records) {
            QueryWrapper<Job> jb = new QueryWrapper<>();
            jb.eq("mid",record.getId());
            Long aLong = jobMapper.selectCount(jb);
            Job job = new Job();
            job.setNum(Integer.parseInt(String.valueOf(aLong)));
            record.setJob(job);
            record.setCampus(campusMapper.selectById(record.getCid()));
        }
        return majorPage;
    }

    @Override
    public JsonRes addMajor(Major major) {
        QueryWrapper<Major> qw = new QueryWrapper<>();
        qw.eq("name",major.getName());
        qw.eq("cid",major.getCid());
        Major major1 = majorMapper.selectOne(qw);
        if (major1!=null){
            return JsonRes.res(1,"该专业已存在");
        }
        majorMapper.insert(major);
        return JsonRes.res(0,"添加成功");


    }

    @Override
    public JsonRes updateMajor(Major major) {
        majorMapper.updateById(major);
        return JsonRes.res(0,"修改成功");
    }

    @Override
    public JsonRes delMany(Integer[] ids) {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.in("mid", Arrays.asList(ids));
        List<Student> major = studentMapper.selectList(qw);
        if (major.isEmpty()){
            majorMapper.deleteBatchIds(Arrays.asList(ids));
            return JsonRes.res(0,"删除成功");
        }
        else {
            return JsonRes.res(1,"该专业下有学生不能被删除");
        }
    }
}
